package com.usian.filter;

import com.usian.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.lang.annotation.Annotation;

@Component
public class AuthorizeFilter implements GlobalFilter, Order {
    @Override
    public Class<? extends Annotation> annotationType() {
        return null;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)  {
        //1:获取当前请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        try {
            //2：获取当前请求路劲，如果是登录请求 放行
            String path = request.getURI().getPath();
            if(path.contains("/login/in")){
                return chain.filter(exchange);
            }

            //3：获取token来做校验  (是否有token   token有效期)
            String token = request.getHeaders().getFirst("token");

            if(StringUtils.isBlank(token)){
                //如果token没有 怎返回401错误提示码
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            //判断token有效期
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int result = AppJwtUtil.verifyToken(claims);
            if(result==0 || result==-1){
                //有效   解密取出来token id   放到网关请求头中 路由到下游服务-admin
                Integer id = (Integer) claims.get("id");
                ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                    //路由到admin userid
                    httpHeaders.add("userId", id + "");
                }).build();
                exchange.mutate().request(serverHttpRequest).build();

            }
        }catch (Exception e){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        return chain.filter(exchange);
    }

    @Override
    public int value() {
        return 0;
    }
}
